package com.andrew.demo.dao;

import com.andrew.demo.mapper.BaseMapper;
import com.andrew.demo.mapper.MapperHelper;
import com.andrew.demo.mapper.UserMapper;
import com.andrew.demo.model.BaseDbEntity;
import com.andrew.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

@Repository
@Transactional
public abstract class BaseDaoImpl<T extends BaseDbEntity> extends NamedParameterJdbcDaoSupport implements BaseDao<T> {

    /**
     * 具体操作的实体类对象
     */
    private Class<T> entityClass;

    @Autowired
    private MapperHelper mapperHelper;
    /**
     * 具体操作的实体类对象
     */
    BaseMapper rowMapper;

    @Autowired
    public BaseDaoImpl(DataSource dataSource) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        this.setDataSource(dataSource);
        entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        rowMapper = mapperHelper.getRowMapperByClass(entityClass.getSimpleName());
    }

    @Override
    public List<T> QueryList() {
        String sql = rowMapper.TableInfoEntity.SELECT_SQL;
        List<T> list = this.getJdbcTemplate().query(sql, rowMapper);
        return list;
    }

    @Override
    public List<T> QueryList(T t) throws NoSuchFieldException {


        String tableName = rowMapper.TableInfoEntity.TABLE_NAME;
        System.out.println(tableName);

        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        System.out.println("根据字段名来获取字段");
        Field field = entityClass.getDeclaredField("name");
        System.out.println(field.getName());

        String sql = rowMapper.TableInfoEntity.SELECT_SQL;
        sql = sql + " where 1=1 and  id>:id";

        User user = new User();
        user.setId(0);
        SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(user);
        UserMapper userMapper = new UserMapper();
        List<T> list = super.getNamedParameterJdbcTemplate().query(sql, namedParameters, rowMapper);
        return list;
    }

}
